package com.boat.starter.p6spy.listener;

import java.sql.SQLException;

import com.boat.starter.p6spy.context.Context;
import com.boat.starter.p6spy.context.Context.SqlLogInfo;
import com.p6spy.engine.common.P6LogQuery;
import com.p6spy.engine.common.ResultSetInformation;
import com.p6spy.engine.common.StatementInformation;
import com.p6spy.engine.logging.Category;
import com.p6spy.engine.logging.LoggingEventListener;

/**
 * 扩展代码，用于打印sql返回记录数
 * 
 * @author 周江
 *
 */

public class CustomLoggingEventListener extends LoggingEventListener {
	@Override
	public void onAfterAnyExecute(StatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
		SqlLogInfo info = new SqlLogInfo();
		info.setTimes(timeElapsedNanos);
		info.setSql(statementInformation.getSqlWithValues());
		info.setPrepared(statementInformation.getSql());
		info.setUrl(statementInformation.getConnectionInformation().getUrl());
		info.setConnectionId(statementInformation.getConnectionInformation().getConnectionId());
		Context.setSqlLogInfo(info);
		
		if(!info.isSelectSql()) {
			//非select语句，执行sql后立即打印。select语句，因为需要获取结果集记录数，在结果集关闭时再打印
			logElapsed(statementInformation, timeElapsedNanos, Category.STATEMENT, e);
			Context.clear();
		}
	}
	
	@Override
	  public void onAfterResultSetNext(ResultSetInformation resultSetInformation, long timeElapsedNanos, boolean hasNext, SQLException e) {
	    if (hasNext) {
	      logElapsed(resultSetInformation, timeElapsedNanos, Category.RESULT, e);
	      
	      //当调用next方法时，累加结果集数量
	      Context.getSqlLogInfo().incRowCount();
	    }
	  }

	  @Override
	  public void onAfterResultSetClose(ResultSetInformation resultSetInformation, SQLException e) {
	    if (resultSetInformation.getCurrRow() > -1) {
	      // If the result set has not been advanced to the first row, there is nothing to log.
	      resultSetInformation.generateLogMessage();
	    }
	    
	    //打印select查询
	    SqlLogInfo info = Context.getSqlLogInfo();
	    if(info.isSelectSql()) {
	    	P6LogQuery.getLogger().logSQL(info.getConnectionId(), "", info.getTimes(), Category.INFO, info.getPrepared(), info.getSql(), info.getUrl());
	    }
	    Context.clear();
	  }

}
